﻿using Wabo.Dal.Repository;
using Wabo.Web.Areas.Manager.Core.Exceptions;
using System;
using System.Web.Mvc;
using System.Web.Routing;
using Wabo.Web.Areas.Manager.ViewModels;

namespace Wabo.Web.Areas.Manager.Core.Attributes
{    
    /// <summary>
    /// Base class for ACL related attributes
    /// Redirects user to access error page based on the permission exception
    /// </summary>
    public class WaboPermissionAttribute : ActionFilterAttribute
    {
        protected bool ByPass { get; set; }
        protected Exception PermissionException { get; set; }

        public WaboPermissionAttribute(bool byPass,Exception ex)            
        {
            ByPass = byPass;
            PermissionException = ex;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            
            string moduleName = filterContext.Controller.GetType().Name.Replace("Controller", "");
            using (var mc = new WaboEFModuleRepository())
            {
                var canContinue = false;

                if( PermissionException is NoListPermissionException )
                    canContinue = mc.UserCanList(SessionManager.AuthorizedUser(), mc.Get(moduleName));
                else if (PermissionException is NoReadPermissionException)
                    canContinue = mc.UserCanRead(SessionManager.AuthorizedUser(), mc.Get(moduleName));
                else if (PermissionException is NoWritePermissionException)
                    canContinue = mc.UserCanWrite(SessionManager.AuthorizedUser(), mc.Get(moduleName));
                else if (PermissionException is NoDeletePermissionException)
                    canContinue = mc.UserCanDelete(SessionManager.AuthorizedUser(), mc.Get(moduleName));

                if ( !canContinue && !ByPass)
                {
                    var errorModel = new AccessErrorViewModel
                    {
                        ErrorException = PermissionException
                    };
                    var redirectRoute = new RouteValueDictionary
                        {
                            {"Controller","AccessError"},
                            {"Action","Index"}                            
                        };
                    filterContext.Controller.TempData[AccessErrorViewModel.TempdataParameterName] = errorModel;
                    filterContext.Result = new RedirectToRouteResult(redirectRoute);
                    return;
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
}